
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_Hans">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>File 对象 &#8212; Django 3.2.11.dev 文档</title>
    <link rel="stylesheet" href="../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../_static/doctools.js"></script>
    <script type="text/javascript" src="../../_static/language_data.js"></script>
    <link rel="index" title="索引" href="../../genindex.html" />
    <link rel="search" title="搜索" href="../../search.html" />
    <link rel="next" title="文件存储 API" href="storage.html" />
    <link rel="prev" title="文件处理" href="index.html" />



 
<script src="../../templatebuiltins.js"></script>
<script>
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);</script>

  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../../index.html">Django 3.2.11.dev 文档</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../../index.html">Home</a>  |
        <a title="Table of contents" href="../../contents.html">Table of contents</a>  |
        <a title="Global index" href="../../genindex.html">Index</a>  |
        <a title="Module index" href="../../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="index.html" title="文件处理">previous</a>
     |
    <a href="../index.html" title="API 参考" accesskey="U">up</a>
   |
    <a href="storage.html" title="文件存储 API">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="ref-files-file">
            
  <div class="section" id="s-the-file-object">
<span id="the-file-object"></span><h1><code class="docutils literal notranslate"><span class="pre">File</span></code> 对象<a class="headerlink" href="#the-file-object" title="永久链接至标题">¶</a></h1>
<p><a class="reference internal" href="index.html#module-django.core.files" title="django.core.files: File handling and storage"><code class="xref py py-mod docutils literal notranslate"><span class="pre">django.core.files</span></code></a> 模块及其子模块包含了 Django 中基本的文件处理的内置类。</p>
<div class="section" id="s-the-file-class">
<span id="the-file-class"></span><h2><code class="docutils literal notranslate"><span class="pre">File</span></code> 类<a class="headerlink" href="#the-file-class" title="永久链接至标题">¶</a></h2>
<dl class="class">
<dt id="django.core.files.File">
<em class="property">class </em><code class="descname">File</code>(<em>file_object</em>, <em>name=None</em>)<a class="reference internal" href="../../_modules/django/core/files/base.html#File"><span class="viewcode-link">[源代码]</span></a><a class="headerlink" href="#django.core.files.File" title="永久链接至目标">¶</a></dt>
<dd><p><a class="reference internal" href="#django.core.files.File" title="django.core.files.File"><code class="xref py py-class docutils literal notranslate"><span class="pre">File</span></code></a> 类是对 Python <a class="reference external" href="https://docs.python.org/3/glossary.html#term-file-object" title="(在 Python v3.10)"><span class="xref std std-term">file object</span></a> 的一个简单的封装，并增加了一些 Django 特有的功能。在内部，当 Django 需要表示一个文件时，会使用这个类。</p>
<p><a class="reference internal" href="#django.core.files.File" title="django.core.files.File"><code class="xref py py-class docutils literal notranslate"><span class="pre">File</span></code></a> 对象具有以下属性和方法：</p>
<dl class="attribute">
<dt id="django.core.files.File.name">
<code class="descname">name</code><a class="headerlink" href="#django.core.files.File.name" title="永久链接至目标">¶</a></dt>
<dd><p>文件名，包括 <a class="reference internal" href="../settings.html#std:setting-MEDIA_ROOT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">MEDIA_ROOT</span></code></a> 的相对路径。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.core.files.File.size">
<code class="descname">size</code><a class="headerlink" href="#django.core.files.File.size" title="永久链接至目标">¶</a></dt>
<dd><p>文件的大小，单位为字节。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.core.files.File.file">
<code class="descname">file</code><a class="headerlink" href="#django.core.files.File.file" title="永久链接至目标">¶</a></dt>
<dd><p>该类封装的底层 <a class="reference external" href="https://docs.python.org/3/glossary.html#term-file-object" title="(在 Python v3.10)"><span class="xref std std-term">file object</span></a>。</p>
<div class="admonition-be-careful-with-this-attribute-in-subclasses admonition">
<p class="first admonition-title">在子类中要小心这个属性。</p>
<p class="last">一些 <a class="reference internal" href="#django.core.files.File" title="django.core.files.File"><code class="xref py py-class docutils literal notranslate"><span class="pre">File</span></code></a> 的子类，包括 <a class="reference internal" href="#django.core.files.base.ContentFile" title="django.core.files.base.ContentFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentFile</span></code></a> 和 <code class="xref py py-class docutils literal notranslate"><span class="pre">FieldFile</span></code>，可以用 Python <a class="reference external" href="https://docs.python.org/3/glossary.html#term-file-object" title="(在 Python v3.10)"><span class="xref std std-term">file object</span></a> 以外的对象来替换这个属性。在这些情况下，这个属性本身可能是一个 <a class="reference internal" href="#django.core.files.File" title="django.core.files.File"><code class="xref py py-class docutils literal notranslate"><span class="pre">File</span></code></a> 子类（而且不一定是同一个子类）。只要有可能，就使用子类本身的属性和方法，而不是子类的 <code class="docutils literal notranslate"><span class="pre">file</span></code> 属性。</p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="django.core.files.File.mode">
<code class="descname">mode</code><a class="headerlink" href="#django.core.files.File.mode" title="永久链接至目标">¶</a></dt>
<dd><p>文件的读／写模式。</p>
</dd></dl>

<dl class="method">
<dt id="django.core.files.File.open">
<code class="descname">open</code>(<em>mode=None</em>)<a class="reference internal" href="../../_modules/django/core/files/base.html#File.open"><span class="viewcode-link">[源代码]</span></a><a class="headerlink" href="#django.core.files.File.open" title="永久链接至目标">¶</a></dt>
<dd><p>打开或重新打开文件（它也做 <code class="docutils literal notranslate"><span class="pre">File.seek(0)</span></code>）。<code class="docutils literal notranslate"><span class="pre">mode</span></code> 参数允许的值与 Python 内置的 <a class="reference external" href="https://docs.python.org/3/library/functions.html#open" title="(在 Python v3.10)"><code class="docutils literal notranslate"><span class="pre">open()</span></code></a> 相同。</p>
<p>当重新打开一个文件时，<code class="docutils literal notranslate"><span class="pre">mode</span></code> 将覆盖文件原来打开的任何模式；<code class="docutils literal notranslate"><span class="pre">None</span></code> 表示用原来的模式重新打开。</p>
<p>它可以作为一个上下文管理器使用，例如 <code class="docutils literal notranslate"><span class="pre">with</span> <span class="pre">file.open()</span> <span class="pre">as</span> <span class="pre">f:</span></code>。</p>
</dd></dl>

<dl class="method">
<dt id="django.core.files.File.__iter__">
<code class="descname">__iter__</code>()<a class="reference internal" href="../../_modules/django/core/files/base.html#File.__iter__"><span class="viewcode-link">[源代码]</span></a><a class="headerlink" href="#django.core.files.File.__iter__" title="永久链接至目标">¶</a></dt>
<dd><p>在文件上迭代，每次只产生一行。</p>
</dd></dl>

<dl class="method">
<dt id="django.core.files.File.chunks">
<code class="descname">chunks</code>(<em>chunk_size=None</em>)<a class="reference internal" href="../../_modules/django/core/files/base.html#File.chunks"><span class="viewcode-link">[源代码]</span></a><a class="headerlink" href="#django.core.files.File.chunks" title="永久链接至目标">¶</a></dt>
<dd><p>对文件进行迭代，产生给定大小的“块”。<code class="docutils literal notranslate"><span class="pre">chunk_size</span></code> 默认为 64KB。</p>
<p>这对非常大的文件特别有用，因为它允许将它们从磁盘上串联起来，避免将整个文件存储在内存中。</p>
</dd></dl>

<dl class="method">
<dt id="django.core.files.File.multiple_chunks">
<code class="descname">multiple_chunks</code>(<em>chunk_size=None</em>)<a class="reference internal" href="../../_modules/django/core/files/base.html#File.multiple_chunks"><span class="viewcode-link">[源代码]</span></a><a class="headerlink" href="#django.core.files.File.multiple_chunks" title="永久链接至目标">¶</a></dt>
<dd><p>如果文件足够大，需要多个分块才能访问其所有内容，则返回 <code class="docutils literal notranslate"><span class="pre">True</span></code>。</p>
</dd></dl>

<dl class="method">
<dt id="django.core.files.File.close">
<code class="descname">close</code>()<a class="reference internal" href="../../_modules/django/core/files/base.html#File.close"><span class="viewcode-link">[源代码]</span></a><a class="headerlink" href="#django.core.files.File.close" title="永久链接至目标">¶</a></dt>
<dd><p>关闭文件。</p>
</dd></dl>

<p>除了列出的方法外，<a class="reference internal" href="#django.core.files.File" title="django.core.files.File"><code class="xref py py-class docutils literal notranslate"><span class="pre">File</span></code></a> 还暴露了它的 <code class="docutils literal notranslate"><span class="pre">file</span></code> 对象的以下属性和方法：<code class="docutils literal notranslate"><span class="pre">encoding</span></code>、<code class="docutils literal notranslate"><span class="pre">fileno</span></code>、<code class="docutils literal notranslate"><span class="pre">flush</span></code>、<code class="docutils literal notranslate"><span class="pre">isat</span></code>。<code class="docutils literal notranslate"><span class="pre">encoding</span></code>、<code class="docutils literal notranslate"><span class="pre">fileno</span></code>、<code class="docutils literal notranslate"><span class="pre">flush</span></code>、<code class="docutils literal notranslate"><span class="pre">isatty</span></code>、<code class="docutils literal notranslate"><span class="pre">newlines</span></code>、<code class="docutils literal notranslate"><span class="pre">read</span></code>、<code class="docutils literal notranslate"><span class="pre">readinto</span></code>、<code class="docutils literal notranslate"><span class="pre">readline</span></code>、<code class="docutils literal notranslate"><span class="pre">readlines</span></code>、<code class="docutils literal notranslate"><span class="pre">seek</span></code>、<code class="docutils literal notranslate"><span class="pre">tell</span></code>、<code class="docutils literal notranslate"><span class="pre">truncate</span></code>、<code class="docutils literal notranslate"><span class="pre">write</span></code>、<code class="docutils literal notranslate"><span class="pre">writelines</span></code>、<code class="docutils literal notranslate"><span class="pre">readable()</span></code>、<code class="docutils literal notranslate"><span class="pre">writable()</span></code> 和 <code class="docutils literal notranslate"><span class="pre">seekable()</span></code>。</p>
</dd></dl>

</div>
<div class="section" id="s-the-contentfile-class">
<span id="the-contentfile-class"></span><h2><code class="docutils literal notranslate"><span class="pre">ContentFile</span></code> 类<a class="headerlink" href="#the-contentfile-class" title="永久链接至标题">¶</a></h2>
<dl class="class">
<dt id="django.core.files.base.ContentFile">
<em class="property">class </em><code class="descname">ContentFile</code>(<em>content</em>, <em>name=None</em>)<a class="reference internal" href="../../_modules/django/core/files/base.html#ContentFile"><span class="viewcode-link">[源代码]</span></a><a class="headerlink" href="#django.core.files.base.ContentFile" title="永久链接至目标">¶</a></dt>
<dd><p><code class="docutils literal notranslate"><span class="pre">ContentFile</span></code> 类继承自 <a class="reference internal" href="#django.core.files.File" title="django.core.files.File"><code class="xref py py-class docutils literal notranslate"><span class="pre">File</span></code></a>，但与 <a class="reference internal" href="#django.core.files.File" title="django.core.files.File"><code class="xref py py-class docutils literal notranslate"><span class="pre">File</span></code></a> 不同的是，它操作的是字符串内容（也支持字节），而不是实际的文件。例如：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.core.files.base</span> <span class="kn">import</span> <span class="n">ContentFile</span>

<span class="n">f1</span> <span class="o">=</span> <span class="n">ContentFile</span><span class="p">(</span><span class="s2">&quot;esta frase está en español&quot;</span><span class="p">)</span>
<span class="n">f2</span> <span class="o">=</span> <span class="n">ContentFile</span><span class="p">(</span><span class="sa">b</span><span class="s2">&quot;these are bytes&quot;</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

</div>
<div class="section" id="s-the-imagefile-class">
<span id="the-imagefile-class"></span><h2><code class="docutils literal notranslate"><span class="pre">ImageFile</span></code> 类<a class="headerlink" href="#the-imagefile-class" title="永久链接至标题">¶</a></h2>
<dl class="class">
<dt id="django.core.files.images.ImageFile">
<em class="property">class </em><code class="descname">ImageFile</code>(<em>file_object</em>, <em>name=None</em>)<a class="reference internal" href="../../_modules/django/core/files/images.html#ImageFile"><span class="viewcode-link">[源代码]</span></a><a class="headerlink" href="#django.core.files.images.ImageFile" title="永久链接至目标">¶</a></dt>
<dd><p>Django 提供了一个专门针对图片的内置类。 <a class="reference internal" href="#django.core.files.images.ImageFile" title="django.core.files.images.ImageFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">django.core.files.images.ImageFile</span></code></a> 继承了 <a class="reference internal" href="#django.core.files.File" title="django.core.files.File"><code class="xref py py-class docutils literal notranslate"><span class="pre">File</span></code></a> 的所有属性和方法，并额外提供了以下内容。</p>
<dl class="attribute">
<dt id="django.core.files.images.ImageFile.width">
<code class="descname">width</code><a class="headerlink" href="#django.core.files.images.ImageFile.width" title="永久链接至目标">¶</a></dt>
<dd><p>图像的宽度，单位为像素。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.core.files.images.ImageFile.height">
<code class="descname">height</code><a class="headerlink" href="#django.core.files.images.ImageFile.height" title="永久链接至目标">¶</a></dt>
<dd><p>图像的高度，单位为像素。</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="s-additional-methods-on-files-attached-to-objects">
<span id="additional-methods-on-files-attached-to-objects"></span><h2>附加在对象上的文件方法<a class="headerlink" href="#additional-methods-on-files-attached-to-objects" title="永久链接至标题">¶</a></h2>
<p>任何与对象相关联的 <a class="reference internal" href="#django.core.files.File" title="django.core.files.File"><code class="xref py py-class docutils literal notranslate"><span class="pre">File</span></code></a> （如下面的 <code class="docutils literal notranslate"><span class="pre">Car.photo</span></code>）也会有几个额外的方法：</p>
<dl class="method">
<dt id="django.core.files.File.save">
<code class="descclassname">File.</code><code class="descname">save</code>(<em>name</em>, <em>content</em>, <em>save=True</em>)<a class="headerlink" href="#django.core.files.File.save" title="永久链接至目标">¶</a></dt>
<dd><p>使用提供的文件名和内容保存一个新文件。这不会替换现有的文件，但会创建一个新的文件并更新对象以指向它。如果 <code class="docutils literal notranslate"><span class="pre">save</span></code> 为 <code class="docutils literal notranslate"><span class="pre">True</span></code>，文件保存后将调用模型的 <code class="docutils literal notranslate"><span class="pre">save()</span></code> 方法。也就是这两行：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">car</span><span class="o">.</span><span class="n">photo</span><span class="o">.</span><span class="n">save</span><span class="p">(</span><span class="s1">&#39;myphoto.jpg&#39;</span><span class="p">,</span> <span class="n">content</span><span class="p">,</span> <span class="n">save</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">car</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
</pre></div>
</div>
<p>等价于：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">car</span><span class="o">.</span><span class="n">photo</span><span class="o">.</span><span class="n">save</span><span class="p">(</span><span class="s1">&#39;myphoto.jpg&#39;</span><span class="p">,</span> <span class="n">content</span><span class="p">,</span> <span class="n">save</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</pre></div>
</div>
<p>请注意，<code class="docutils literal notranslate"><span class="pre">content</span></code> 参数必须是 <a class="reference internal" href="#django.core.files.File" title="django.core.files.File"><code class="xref py py-class docutils literal notranslate"><span class="pre">File</span></code></a> 或 <a class="reference internal" href="#django.core.files.File" title="django.core.files.File"><code class="xref py py-class docutils literal notranslate"><span class="pre">File</span></code></a> 的子类的实例，如 <a class="reference internal" href="#django.core.files.base.ContentFile" title="django.core.files.base.ContentFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentFile</span></code></a>。</p>
</dd></dl>

<dl class="method">
<dt id="django.core.files.File.delete">
<code class="descclassname">File.</code><code class="descname">delete</code>(<em>save=True</em>)<a class="headerlink" href="#django.core.files.File.delete" title="永久链接至目标">¶</a></dt>
<dd><p>从模型实例中删除文件并删除底层文件。如果 <code class="docutils literal notranslate"><span class="pre">save</span></code> 是 <code class="docutils literal notranslate"><span class="pre">True</span></code>，一旦文件被删除，模型的 <code class="docutils literal notranslate"><span class="pre">save()</span></code> 方法将被调用。</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#"><code class="docutils literal notranslate"><span class="pre">File</span></code> 对象</a><ul>
<li><a class="reference internal" href="#the-file-class"><code class="docutils literal notranslate"><span class="pre">File</span></code> 类</a></li>
<li><a class="reference internal" href="#the-contentfile-class"><code class="docutils literal notranslate"><span class="pre">ContentFile</span></code> 类</a></li>
<li><a class="reference internal" href="#the-imagefile-class"><code class="docutils literal notranslate"><span class="pre">ImageFile</span></code> 类</a></li>
<li><a class="reference internal" href="#additional-methods-on-files-attached-to-objects">附加在对象上的文件方法</a></li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="index.html"
                        title="上一章">文件处理</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="storage.html"
                        title="下一章">文件存储 API</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../../_sources/ref/files/file.txt"
            rel="nofollow">显示源代码</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>快速搜索</h3>
    <div class="searchformwrapper">
    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="转向" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">12月 07, 2021</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="index.html" title="文件处理">previous</a>
     |
    <a href="../index.html" title="API 参考" accesskey="U">up</a>
   |
    <a href="storage.html" title="文件存储 API">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>